package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO add(OrdersSubmitDTO ordersSubmitDTO) {

//      1、  处理业务异常 (地址簿为空、购物车为空)
        AddressBook addressBook = AddressBook.builder()
                .id(ordersSubmitDTO.getAddressBookId())
                .build();
        List<AddressBook> addressBooks = addressBookMapper.find(addressBook);
//        地址簿判空
        if (addressBooks==null || addressBooks.size()==0) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        addressBook=addressBooks.get(0);

        ShoppingCart cart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> Carts = shoppingCartMapper.find(cart);
//        购物车判空
        if (Carts==null || Carts.size()==0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


//      2、  向订单表中插入1条数据(现将数据补全
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(addressBook.getDetail());
        orderMapper.add(orders);

//       3、 向订单明细表中插入n条数据
        for (ShoppingCart shoppingCart : Carts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.add(orderDetail);
        }

//       4、 清空购物车数据
        shoppingCartMapper.clean(BaseContext.getCurrentId());
//       5、  封装VO
        OrderSubmitVO orderSubmitVO =OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
//          TODO 支付流程没有实现

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

//        实现假支付
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return null;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);


    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
//        通过订单id查找订单
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        if(order!=null ) {
            //        修改订单取消相关信息
            order.setCancelReason(ordersCancelDTO.getCancelReason());
            order.setStatus(Orders.CANCELLED);
            order.setCancelTime(LocalDateTime.now());
            order.setPayStatus(Orders.REFUND);
//         TODO 退款流程没有实现，现在只是单纯的修改了状态
            orderMapper.update(order);
        }
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        OrderStatisticsVO vo = OrderStatisticsVO.builder()
                .confirmed(orderMapper.countStatus(Orders.CONFIRMED))
                .toBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED))
                .deliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS))
                .build();
        return vo;
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        Orders order = orderMapper.getById(id);
        if(order==null || order.getStatus()!=Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 拒绝订单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
//       用户下单给商家进行接单，商家拒绝接单（退钱、状态进行修改）
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());
        if(order==null || order.getStatus()!=Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setPayStatus(Orders.REFUND);
//         TODO 退款流程没有实现，现在只是单纯的修改了状态

        orderMapper.update(order);
    }

    /**
     * 接单
     * @param id
     */
    @Override
    public void confirm(Long id) {
//        接单：修改订单状态
        Orders order = orderMapper.getById(id);
        if(order==null || order.getStatus()!=Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.CONFIRMED);
        orderMapper.update(order);
    }

    /**
     * 查询id对应订单信息
     * @param id
     * @return
     */
    @Override
//    获取订单详细信息
    public OrderVO getById(Long id) {
//        先从表中找到对应的订单
        OrderVO vo=new OrderVO();
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        BeanUtils.copyProperties(order, vo);
        vo.setOrderDetailList(orderDetailMapper.getByOrderId(id));
        return vo;
    }

    /**
     * 派送
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null && order.getStatus()!=Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /**
     * 分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
//        通过 时间、编号、手机进行查找
        List<OrderVO> orders =orderMapper.find(ordersPageQueryDTO);
        for (OrderVO order : orders) {
            order.setOrderDishes(getOrderDishesStr(order.getId()));
        }
        Page<OrderVO> page = (Page<OrderVO>) orders;

        PageResult pageBean=new PageResult(page.getTotal(), page.getResult());
        return  pageBean;
    }

    /**
     * 将订单详细转换为文字
     * @param orderId
     * @return
     */
    private String getOrderDishesStr(Long orderId) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    @Override
    public void repetition(Long id) {
//        再来一单就 将 订单中购买过的菜品加入到 购物车中
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);
        for (OrderDetail detail : list) {
//      userid、createTime加入
            ShoppingCart cart=new ShoppingCart();
            BeanUtils.copyProperties(detail, cart);
//          放入对应 userid
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.add(cart);
        }

    }

    @Override
    public PageResult pageUserQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
//        通过 时间、编号、手机进行查找
        List<OrderVO> orders =orderMapper.find(ordersPageQueryDTO);
        for (OrderVO order : orders) {
            order.setOrderDetailList(orderDetailMapper.getByOrderId(order.getId()));
        }
        Page<OrderVO> page = (Page<OrderVO>) orders;
        PageResult pageBean=new PageResult(page.getTotal(), page.getResult());

        return pageBean;
    }

    @Override
    public void reminder(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        if(ordersDB==null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+ordersDB.getNumber());
        String json=JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }


}
